#!/bin/bash

set -o xtrace
# floating ips
# Default floating IP pool name
KEYPAIR_NAME=`euca-describe-keypairs | head -n1 | cut -f2`
IMAGE=`euca-describe-images | grep machine | head -n1 | cut -f2`
INSTANCE_TYPE=${INSTANCE_TYPE:-"m1.tiny"}
INSTANCE_ID=`euca-run-instances $IMAGE -k $KEYPAIR_NAME -t $INSTANCE_TYPE | grep INSTANCE | cut -f2`
ACTIVE_TIMEOUT=${ACTIVE_TIMEOUT:-45}
if ! timeout $ACTIVE_TIMEOUT sh -c "while ! euca-describe-instances $INSTANCE_ID | grep -q running; do sleep 1; done"; then
	echo "Instance $INSTANCE_ID didn't become active in $ACTIVE_TIMEOUT"
	exit 1
fi
DEFAULT_FLOATING_POOL=${DEFAULT_FLOATING_POOL:-"nova"}
FLOATING_RANGE=${FLOATING_RANGE:-"192.168.168.224/28"}
INSTANCE_IP=`euca-describe-instances $INSTANCE_ID | grep INSTANCE | cut -f4`
sudo nova-manage floating create $FLOATING_RANGE
FLOATING_IP=`euca-allocate-address | cut -f2`
euca-associate-address -i $INSTANCE_ID $FLOATING_IP
euca-authorize -P icmp -t -1:-1 default
euca-authorize -P tcp -p 22 default

exit 0